<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="160px" v-show="showSearch">
            <el-row>
                <el-form-item label="省" prop="dkpProvinceId">
                    <el-select v-model="queryParams.dkpProvinceId" placeholder="请选择省" @change="chooseProvince"
                        clearable>
                        <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="市" prop="dkpCityId">
                    <el-select v-model="queryParams.dkpCityId" placeholder="请选择市" @change="chooseCity" clearable>
                        <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="区/县" prop="dkpPrefectureId">
                    <el-select v-model="queryParams.dkpPrefectureId" placeholder="请选择区/县" clearable>
                        <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-row>
            <el-row>
                <el-form-item label="重大工程基础设施类型" prop="dkpKeyType">
                    <el-select v-model="queryParams.dkpKeyType" placeholder="请选择" clearable>
                        <el-option v-for="(key,val) in optionCode['dkpKeyType']" :key="key" :label="key" :value="val">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button plain @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8" style="float:left">
            <el-col :span="1.5" v-if="isAdminShow">
                <el-button plain icon="Delete" @click="handleDelete">删除</el-button>
            </el-col>
            <el-col :span="1.5" v-if="isAdminShow">
                <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Edit" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Download" @click="handleImport">导入</el-button>
            </el-col>
            
        </el-row>
        <div style="text-align: right;float: right;">
            <span>排列方式：</span>
            <el-radio-group v-model="queryParams.option" @change="handleQuery">
                <el-radio label="0">行政区划</el-radio>
                <el-radio label="1">更新时间倒序</el-radio>
            </el-radio-group>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </div>

        <el-table v-loading="loading" :data="dataList" :border="true" @selection-change="selectChange" row-key="dkpId" stripe>
            <el-table-column type="selection" width="55" align="center" reserve-selection />
            <el-table-column label="省" align="center" prop="dkpProvince" />
            <el-table-column label="市" align="center" prop="dkpCity" />
            <el-table-column label="区（县）" align="center" prop="dkpPrefecture" />
            <el-table-column label="重大工程基础设施类型" align="center" prop="dkpKeyType">
                <template #default="{row}">
                    {{optionCode['dkpKeyType'][row.dkpKeyType]}}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isAdminShow">
                <template #default="{row}">
                    <el-button type="text" @click="handleUpdate(row)">修改</el-button>
                    <el-button type="text" @click="handleUpdate(row, true)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.rows" @pagination="getList" />

        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <p></p>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
                :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError"
                :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                            download="重大工程基础设施模板-核工程" @click="importTemplate">模板下载</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button plain @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 新增对话框 -->
        <AddOrUpdate v-model:open="addOrUpdateShow" @getList="getList" v-model:curId="curId"
            v-model:isDisabled="isDisabled"></AddOrUpdate>
    </div>
</template>
<script setup>
import { getQueryList, deleteDkp } from '@/api/basedatamanage/majorProject'
import { getToken } from "@/utils/auth";
import AddOrUpdate from './addOrUpdate.vue'
import { useMajorProjectStore } from '@/store/modules/majorProject'
import { getLanderRoles, getLanderProvince } from "@/api/basedatamanage/common.js"

const optionCode = {
    'dkpKeyType': { '0': '核工程', '1': '水利水电工程', '2': '石油化工工程', '3': '交通运输工程', '4': '科学实验和重大科学装置工程', '5': '其他' }
}
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        dkpProvinceId: '',
        dkpCityId: '',
        dkpPrefectureId: '',
        dkpKeyType: '',
        option: '0'
    },
    total: 0,
    dataList: [],
    cityData: [], // 市
    areaData: [], //区、县
    curId: ''
})
let { queryParams, dataList, total, cityData, areaData, curId } = toRefs(data)
/* 用户导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "token " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/keyProject/importExcel/"
});
const addOrUpdateShow = ref(false)
const isDisabled = ref(false)

const loading = ref(false);
const showSearch = ref(true);

const { proxy } = getCurrentInstance();

/* 省、市、区/县 */
const majorProject = useMajorProjectStore()
const { provinceData } = storeToRefs(majorProject)
const { getProvinceData, getCityData, getAreaData } = majorProject

onMounted(() => {
    getDefaultProvice()
    getProvinceData()
})
const chooseProvince = async (value) => {
    queryParams.value.dkpCityId = null;
    queryParams.value.dkpPrefectureId = null;
    cityData.value = [];
    areaData.value = [];
    cityData.value = await getCityData(value)
}
const chooseCity = async (value) => {
    queryParams.value.dkpPrefectureId = null;
    areaData.value = [];
    areaData.value = await getAreaData(value)
}

/* 获取重大工程基础设施数据列表 */
const getList = async () => {
    loading.value = true;
    let res = await getQueryList(queryParams.value)
    loading.value = false;
    dataList.value = res.data.rows
    total.value = res.data.total
}

/* 查询 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}
/* 重置 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}
// 新增
const handleAdd = function () {
    addOrUpdateShow.value = true;
    proxy.resetForm('detailRef')
}
// 修改|查看
const handleUpdate = (row, flag) => {
    addOrUpdateShow.value = true
    isDisabled.value = flag
    curId.value = row.dkpId
}
// 删除
const handleDelete = () => {
    proxy.$modal.confirm('是否确认删除？').then(() => {
        deleteDkp(ids.value.join(',')).then(res => {
            if (res.code == 200) {
                proxy.$modal.msgSuccess('删除成功！')
                getList()
            }
        })
    })
}
// 导入
const handleImport = () => {
    if (queryParams.value.dkpKeyType == '') {
        proxy.$modal.msgError('请选择重大工程基础设施类型！')
        return
    }
    upload.title = "导入";
    upload.open = true;
    upload.url = import.meta.env.VITE_APP_BASE_API + "/keyProject/importExcel/" + queryParams.value.dkpKeyType
}
// 导出
const handleExport = () => {
    if (queryParams.value.dkpKeyType == '') {
        proxy.$modal.msgError('请选择重大工程基础设施类型！')
        return
    }
    proxy.download('keyProject/exportExcel', {
        ...queryParams.value
    }, `重大工程基础设施_${new Date().getTime()}.xls`)
}

const ids = ref()
const selectChange = (selection) => {
    ids.value = selection.map(item => item.dkpId);
}

// 模板下载
const importTemplate = () => {
    let name = ''
    let dkpKeyType = queryParams.value.dkpKeyType;
    if (dkpKeyType == '0') {
        name = '重大工程基础设施数据模板-核工程.xlsx'
    } else if (dkpKeyType == '1') {
        name = '重大工程基础设施数据模板-水利水电工程.xlsx'
    } else if (dkpKeyType == '2') {
        name = '重大工程基础设施数据模板-石油化工工程.xlsx'
    } else if (dkpKeyType == '3') {
        name = '重大工程基础设施数据模板-交通运输工程.xlsx'
    } else if (dkpKeyType == '4') {
        name = '重大工程基础设施数据模板-科学实验和重大科学装置工程.xlsx'
    } else if (dkpKeyType == '5') {
        name = '重大工程基础设施数据模板-其他.xlsx'
    }
    if (name) {
        proxy.download("/base/product/downloadExcel", {
            fileName: name
        }, name);
    }
}


/* 文件上传前处理 */
function handleFileBeforeUpload(file) {
    console.log('上传前')
    proxy.$modal.loading("正在导入文件，请稍候...");
    return true
}

/* 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("导入文件失败");
}
/* 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$modal.closeLoading();
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    queryParams.value.page = 1;
    getList();
};

/* 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};
// 权限
const isAdminShow = ref(false)
const isAdmin = async () => {
    let res = await getLanderRoles()
    const { code, data } = res
    if(code == 200) {
        const auth = data.split(',')
        if(auth.includes('国家业务员') && auth.length == 1 ){
            isAdminShow.value = false
        }else {
            isAdminShow.value = true
        }
        return auth
    }else {
        return Promise.reject(new Error(data))
    }
}
const getDefaultProvice = async () => {
    try {
        let curAuth = await isAdmin()
        const type1 = curAuth.length == 1 && (curAuth.includes('省管理员') || curAuth.includes('省业务员'))
        const type2 = curAuth.length == 2 && curAuth.includes('省管理员') && curAuth.includes('省业务员')
        if(type1 || type2){
            getLanderProvince().then(res => {
                if(res.code == 200){
                    queryParams.value.dkpProvinceId = res.data
                    chooseProvince(queryParams.value.dkpProvinceId)
                    getList()
                }
            })
        }else{
            getList()
        }
    } catch (error) {
        
    }
}
</script>
  
<style lang="scss" scoped>
.down-template {
    text-align: end;
}
</style>